package ntd.util.frame.javacv.task;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.cron.CronUtil;
import com.modular.extra.ai.FactoryAiOpt;
import ntd.sys.ToolJvm;
import ntd.task.Task;
import ntd.task.bo.TaskInfo;
import ntd.tool.ToolCron;
import ntd.util.UtilCatch;
import ntd.util.frame.javacv.action.bean.VisionModelDo;
import ntd.util.frame.javacv.remote.AiVisionRemote;
import ntd.util.frame.javacv.tool.ToolFtpSync;
import ntd.util.util.ToolDuration;

import java.util.ArrayList;
import java.util.List;

import static ntd.util.frame.javacv.ComVisionApi.analysisRemoteList;

/**
 * 机器视觉轮询分析任务
 */
public class VisionAnalysisSyncLocalTask implements Task {
    @Override
    public TaskInfo info() {
        return new TaskInfo("任务-机器视觉结果同步到本地", "task-vision-analysis-sync-local", new VisionAnalysisSyncLocalTask());
    }

    
    @Override
    public void execute(Object o) {
        List<VisionModelDo> visionModelDos = FactoryAiOpt.OPT_VISION_MODEL.cacheListAll();
        List<String> paths = new ArrayList<>();
        paths.addAll(CollStreamUtil.toList(visionModelDos, VisionModelDo::getPathImg));
        paths.addAll(CollStreamUtil.toList(visionModelDos, VisionModelDo::getPathJson));
        paths.addAll(CollStreamUtil.toList(visionModelDos, VisionModelDo::getPathVideo));
        paths.addAll(CollStreamUtil.toList(visionModelDos, VisionModelDo::getPathCsv));

        for (AiVisionRemote aiVisionRemote : analysisRemoteList()) {
            ToolFtpSync toolFtpSync = aiVisionRemote.getFtpSync();

            ToolDuration.duration(() -> {
                for (String path : paths) {
                    UtilCatch.tryCatchNoRes(() -> toolFtpSync.downloadSync("/" + path));
                }
            }, "文件拷贝");
        }
    }

    public static void main(String[] args) throws Exception {
        VisionAnalysisSyncLocalTask visionAnalysisTask = new VisionAnalysisSyncLocalTask();
        // 设置不允许退出
        ToolJvm.setNoExit();
        // 设置定时任务
        CronUtil.schedule("40 * * * * *", (Runnable) () ->  visionAnalysisTask.execute(null));
        // 启动定时任务
        ToolCron.initTask();
    }
}
